<template>
	<view class="wrap">
		<view class="content">
			<u-form :model="form" ref="uForm">
				<view class="title">用户注册</view>
				<u-form-item prop="username">
					<u-input v-model="form.username" type="text" placeholder="请输入用户名" />
				</u-form-item>
				<u-form-item prop="password">
					<u-input v-model="form.password" type="password" placeholder="请输入密码" />
				</u-form-item>
				<u-form-item prop="pwd2">
					<u-input v-model="form.pwd2" type="password" placeholder="请再次输入密码" />
				</u-form-item>
				<button @tap="register" :style="[inputStyle]" class="login-btn" :disabled="!isFormValid">立即注册</button>
			</u-form>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			form: {
				username: '',
				password: '',
				pwd2: ''
			}
		}
	},
	computed: {
		isFormValid() {
			return this.form.username && this.form.password && this.form.pwd2 && (this.form.password === this.form.pwd2);
		},
		inputStyle() {
			let style = {};
			if (this.isFormValid) {
				style.color = "#fff";
				style.backgroundColor = this.$u.color['warning'];
			}
			return style;
		}
	},
	methods: {
		async register() {
			if (!this.form.username) {
				this.$u.toast('请输入用户名')
				return
			}
			
			if (!this.form.password) {
				this.$u.toast('请输入密码')
				return
			}
			
			if (!this.form.pwd2) {
				this.$u.toast('请再次输入密码')
				return
			}
			
			if (this.form.password !== this.form.pwd2) {
				this.$u.toast('两次输入的密码不一致')
				return
			}
			
			let res = await uniCloud.callFunction({
			    name: 'uni-users',
			    data: {
			        action: 'register',
			        username: this.form.username,
			        password: this.form.password,
			    }
			});
			if (res.result.code === 0) {
			    this.$u.toast('注册成功');
			    this.form.username = '';
			    this.form.password = '';
			    this.form.pwd2 = '';
			    uni.showModal({
			        title: '注册成功',
			        content: '是否返回登录页？',
			        success: (res) => {
			            if (res.confirm) {
			                uni.reLaunch({
			                    url: '/pages/login/login'
			                });
			            }
			        }
			    });
			} else {
			    this.$u.toast(res.result.msg);
			}

		}
	}
};
</script>

<style lang="scss" scoped>
.wrap {
	font-size: 28rpx;
	.content {
		width: 600rpx;
		margin: 80rpx auto 0;

		.title {
			text-align: left;
			font-size: 60rpx;
			font-weight: 500;
			margin-bottom: 100rpx;
		}
		input {
			text-align: left;
			margin-bottom: 10rpx;
			padding-bottom: 6rpx;
		}
		.login-btn {
			margin-top: 40rpx;
			background-color: rgb(253, 243, 208);
			color: #FFFFFF;;
			border: none;
			font-size: 30rpx;
			padding: 12rpx 0;
			
			&::after {
				border: none;
			}
		}
	}
}
</style>
